package com.emm.yixun.customer.service.impl.app.manage;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.emm.yixun.basic.service.*;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.app.AddFollowReqDto;
import com.emm.yixun.common.app.AddFollowResDto;
import com.emm.yixun.common.app.servletentity.ContentListReq;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.Distribution;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.utils.FileUploadPorxyUtil;
import com.emm.yixun.common.utils.SequencesGenerator;

@Service("addFollowManage")
public class AddFollowManage {

	@Autowired
	private CustomerService customerService;
	@Autowired
	private FollowService followService;
	@Autowired
	private ImageService imageService;
	@Autowired
	private UserService userService;
	@Autowired
	private AppPushService appPushService;
	@Autowired
	private ProjectService projectService;
	
	@Autowired
	private DistributionService distributionService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private SignedService signedService;
	
	@Value("${file.serviceUrl}")
	private String fileUploadUrl;
	
	/**
	 * 新增客户跟进
	 * @param reqDto
	 * @return
	 */
	public AddFollowResDto addFollow(AddFollowReqDto reqDto) {
		AddFollowResDto resDto = new AddFollowResDto();
		try{
			//1、新增跟进
			//1.1、跟进为图片或语音时,内容插入图片表: sys_tr_image
			//图片表中的地址,采用small_url,此字段必填
			//2、修改客户表中最新跟进时间 last_follow_time
			Long followId=reqDto.getFollowId();
			/*Customer customer = customerService.selectById(Long.parseLong(reqDto.getCustomerId()));*/
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			List<ContentListReq> contentList = reqDto.getContentList();
			FollowDto followDto = new FollowDto();
			if(null==followId){
				followDto.setCustomerId(Long.parseLong(reqDto.getCustomerId()));
				followDto.setProjectId(reqDto.getProjectId());
				followDto.setProjectCode(reqDto.getProjectCode());
				followDto.setFollowMode(reqDto.getFollowMode());
				followDto.setFollowTime(Calendar.getInstance().getTime());
				followDto.setFollowType(reqDto.getFollowType());
				followDto.setVoiceTime(reqDto.getVoiceTime());
				followDto.setVoiceLocalAddr(reqDto.getVoiceLocalAddr());
				followDto.setMerchantId(reqDto.getMerchantId());
				followDto.setNextFollowContent(reqDto.getNextFollowContent());
				followDto.setNextFollowTime(reqDto.getNextFollowTime());
				followDto.setUserCode(user.getUserCode());
				followDto.setAccessCode(reqDto.getProjectCode());
				followDto.setCreateUserId(Long.parseLong(reqDto.getUserId()));
				followDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				if(FollowTypeEnum.TEXT.getNo().equals(reqDto.getFollowType())){
					//文本,将内容直接进行存储
					String content = "";
					if(contentList != null){
						content = contentList.get(0).getFollowContent();
					}
					followDto.setFollowContent(content);
				}else{
					followDto.setFollowContent("图片或语音内容");
				}
				followDto.setIsSend(IsSendEnum.UNSEND.getNo());
				followDto.setIsRead(IsReadEnum.UNREAD.getNo());
				followDto = followService.create(followDto);
			}else{
				followDto.setId(reqDto.getFollowId());
				followDto.setFollowMode(reqDto.getFollowMode());
				followDto.setFollowTime(Calendar.getInstance().getTime());
				followDto.setFollowType(reqDto.getFollowType());
				followDto.setVoiceTime(reqDto.getVoiceTime());
				followDto.setVoiceLocalAddr(reqDto.getVoiceLocalAddr());
				followDto.setMerchantId(reqDto.getMerchantId());
				followDto.setNextFollowContent(reqDto.getNextFollowContent());
				followDto.setNextFollowTime(reqDto.getNextFollowTime());
				followDto.setCreateUserId(Long.parseLong(reqDto.getUserId()));
				followDto.setUpdateUserId(Long.parseLong(reqDto.getUserId()));
				followDto.setUserCode(user.getUserCode());
				followDto.setAccessCode(reqDto.getProjectCode());
				if(FollowTypeEnum.TEXT.getNo().equals(reqDto.getFollowType())){
					//文本,将内容直接进行存储
					String content = "";
					if(contentList != null){
						content = contentList.get(0).getFollowContent();
					}
					followDto.setFollowContent(content);
				}else{
					followDto.setFollowContent("图片或语音内容");
				}
				followService.update(followDto);
			}

			//推送消息：下次跟进提醒
			/*if(reqDto.getNextFollowContent() !=null && !"".equals(reqDto.getNextFollowContent())){
	   	 		Map<String, String> pushMap = new HashMap<String, String>();
		   	 	pushMap.put("action", "下次跟进提醒");
		   	 	pushMap.put("pushType", "XCGJTX");
		   	 	pushMap.put("projectCode", reqDto.getProjectCode());
		   	 	ProjectDto proDto = new ProjectDto();
		   	 	proDto.setProjectCode(reqDto.getProjectCode());
		   	 	Project project = projectService.selectByDto(proDto);
		   	 	pushMap.put("projectName", project.getProjectName());
				appPushService.pushMessage(reqDto.getUserId(), "你的客户"+customer.getCustomerName()+"需要跟进原因:"+reqDto.getNextFollowContent(),
						"下次跟进提醒", pushMap);
				//更新消息发送状态
				FollowDto entity = new FollowDto();
				entity.setId(followDto.getId());
				entity.setIsSend(IsSendEnum.SEND.getNo());
				followService.update(entity);
			}*/
			if(FollowTypeEnum.IMAGE.getNo().equals(reqDto.getFollowType()) || FollowTypeEnum.VOICE.getNo().equals(reqDto.getFollowType())){
				//新增图片或语音附件
				for(ContentListReq req: contentList){
//					String imgName=SequencesGenerator.getUUID("IMG")+req.getFormat();
					String imgName=null;
					if("2".equals(reqDto.getFollowType())){
						imgName = SequencesGenerator.getUUID("IMG")+reqDto.getImageType();
					}else{
						imgName = SequencesGenerator.getUUID("IMG")+reqDto.getFormat();
					}
					String result=FileUploadPorxyUtil.appPost(fileUploadUrl,req.getFollowContent(),imgName);
					JSONObject resultJson=JSON.parseObject(result);
					String postResult=resultJson.getString("result");
					if(!"1".equals(postResult)){
						resDto.setResult(ResultEnum.FAILURE.getNo());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("图片上传失败");
						return resDto;
					}
					String postUrl=resultJson.getString("url");
					ImageDto imageDto = new ImageDto();
					imageDto.setObjectId(followDto.getId());
					imageDto.setSmallUrl(postUrl);
					imageDto.setImgType(ImgTypeEnum.FOLLOW.getNo());
					imageDto.setMerchantId(followDto.getMerchantId());
					imageDto.setUserCode(followDto.getUserCode());
					imageDto.setAccessCode(followDto.getAccessCode());
					imageDto.setRemark("跟进附件");
					imageDto.setCreateUserId(followDto.getCreateUserId());
					imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					imageService.create(imageDto);
				}
			}/*else if(FollowTypeEnum.VOICE.getNo().equals(reqDto.getFollowType())){
				//上传语音
			}*/

			//判断客户是否存在交易
			boolean aLevelFlag = customerService.checkCustomerLevel(Long.valueOf(reqDto.getCustomerId()));

			//客户跟进新增成功后，修改客户信息表处理状态、最后跟进时间
			CustomerDto cusDto = new CustomerDto();
			cusDto.setId(Long.valueOf(reqDto.getCustomerId()));
			cusDto.setIntentionLevel(reqDto.getIntentionLevel());
			if(aLevelFlag){
				cusDto.setIntentionLevel(IntentionLevelEnum.A.getNo());
			}
			cusDto.setProcessStatus(ProcessStatusEnum.YES.getNo());
			cusDto.setLastFollowTime(new Date());
			cusDto.setUpdateUserId(Long.valueOf(reqDto.getUserId()));
			cusDto.setUpdateTime(new Date());
			customerService.update(cusDto);
			
			//修改分配历史表处理状态
			/*UserDto userDto=new UserDto();
			userDto.setUserCode(customer.getUserCode());
			List<User> userList=userService.selectListByDto(userDto);*/
			DistributionDto distributionDto=new DistributionDto();
			distributionDto.setCustomerId(Long.parseLong(reqDto.getCustomerId()));
			List<Distribution> distributionList=distributionService.selectListByDto(distributionDto);
			if(null!=distributionList){
				for(Distribution db : distributionList){
					if(StringUtils.isNotBlank(db.getProcessStatus()) && db.getProcessStatus().equals(ProcessStatusEnum.YES.getNo())){
						continue;
					}
					String processResult="";
					if(FollowTypeEnum.IMAGE.getNo().equals(reqDto.getFollowType())){
						processResult="图片跟进";
					}else if(FollowTypeEnum.VOICE.getNo().equals(reqDto.getFollowType())){
						processResult="语音跟进";
					}else{
						if(null!=contentList && contentList.size()>0)
						 processResult=contentList.get(0).getFollowContent();
					}
					DistributionDto update=new DistributionDto();
					update.setId(db.getId());
					update.setProcessStatus(ProcessStatusEnum.YES.getNo());
					update.setProcessResult(processResult);
					update.setProcessTime(new Date());
					distributionService.update(update);
				}
			}
			
			resDto.setResult("1");
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增跟进失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
}
